import Vue from 'vue'
import Vuex from 'vuex'
import $api from "../config/api";

Vue.use(Vuex)

const store = new Vuex.Store({
	state: {
		userInfo: uni.getStorageSync('userInfo') || {
		},
		role: uni.getStorageSync('role'),
		token: uni.getStorageSync('token') || '',
	},
	getters: {
		userInfo: state => state.userInfo,
		token: state => state.token,
		role: state => state.role
	},
	mutations: {
		SET_USERINFO(state, userInfo) {
			let _userInfo = {
				...userInfo
			}
			if (userInfo.store) {
				_userInfo.store_id = userInfo.store.id
			} else if (userInfo.storeUser) {
				_userInfo.store_id = userInfo.storeUser.store_id
			}
			uni.setStorageSync('userInfo', _userInfo)
			state.userInfo = _userInfo
		},
		SET_ROLE(state, role) {
			uni.setStorageSync('role', role)
			state.role = role
		},
		SET_TOKEN(state, token) {
			uni.setStorageSync('token', token)
			state.token = token
		},
		LOGOUT(state) {
			state.userInfo = {}
			state.role = null
			state.token = ''
			uni.removeStorageSync('role')
			uni.removeStorageSync('userInfo')
			uni.removeStorageSync('token')
		}
	},
	actions: {
		getUserInfo({ commit, state }) {
			return new Promise((resolve, reject) => {
				console.log(state.userInfo.id, 'sdsa')
				if (state.userInfo.id) {
					$api[state.role === 0 ? 'getSupplierDetail' : 'getPurchaseDetail'](state.userInfo.id).then(res => {
						uni.hideLoading()
						if (res) {
							commit('SET_USERINFO', res)
							resolve(res)
						} else {
							commit('SET_USERINFO', {})
							console.log(this.role)
							if (state.role === 1) {
								uni.navigateTo({
									url: '/pages/login/login1'
								})
							} else {
								uni.navigateTo({
									url: '/pages/login/login'
								})
							}
							reject()
						}
					}).finally(() => {
						uni.hideLoading()
					}).catch(() => {
						console.log(state.role === 1)
						commit('SET_USERINFO', {})
						if (state.role === 1) {
							uni.navigateTo({
								url: '/pages/login/login1'
							})
						} else {
							uni.navigateTo({
								url: '/pages/login/login'
							})
						}
						reject()
					})
				} else {
					console.log('weide那个路上')
					commit('SET_USERINFO', {})
					if (state.role === 1) {
						uni.navigateTo({
							url: '/pages/login/login1'
						})
					} else {
						uni.navigateTo({
							url: '/pages/login/login'
						})
					}
					reject()
				}
			})
		},
		setUserInfo({ commit, state }, userInfo) {
			uni.showLoading()
			$api.updateUser(state.userInfo.id, {
				nickname: userInfo.nickname,
				avatar_url: userInfo.avatar_url,
				phone: userInfo.phone
			}).then(res => {
				commit('SET_USERINFO', userInfo)
			}).finally(() => {
				uni.hideLoading()
			})
		},
	}
})

export default store
